const mysql2 = require("mysql2/promise");
const {mysqlConfig} = require("../config.js");

const pool = mysql2.createPool(mysqlConfig)

const mysql2Service = async (sql, params,isTransaction) => {
    const connection = await pool.getConnection();
    let res = await connection.query(sql, params)
    console.log("-------1-----")
    console.log(res)
    console.log("-------2-----")
    // connection.release();
    return res[0]
};

async function useTransaction(callback) {
    const connection = await pool.getConnection();
    await connection.beginTransaction();
    try {
        callback && await callback()
        await connection.commit();
        console.log('try')
    } catch (e) {
        await connection.rollback();
        throw e;
    } finally {
        console.log('finally')
        connection.release();  //释放连接回连接池
    }
}

module.exports = {
    mysql2Service: mysql2Service,
    useTransaction: useTransaction,
    pool: pool
}
